<?php

namespace app\common\model\mycurrency;

use think\Exception;
use think\Model;
use think\Queue;
use traits\model\SoftDelete;

class LeaseDeposit extends Model
{

    //use SoftDelete;

    // 表名
    protected $name = 'mycurrency_lease_deposit';

    // 追加属性
    protected $append = [
        'status_text'
    ];

    const STATUS_YIQUXIAO = -1;//状态 = 已取消
    const STATUS_ZHIFUCHAOSHI = -2;//状态 = 支付超时
    const STATUS_WEIZHIFU = 1;//状态 = 未支付
    const STATUS_YIZHIFU = 2;//状态 = 已支付
    const STATUS_TUIKUANGZHONG = 3;//状态 = 已退款
    const STATUS_YITUIKUAN = 4;//状态 = 已退款
    const STATUS_YIKOUKUAN= 5;//状态 = 已扣款

    const PAY_TYPE_WECHAT             = 1;//支付类型 = 微信支付
    const PAY_TYPE_ALIPAY             = 2;//支付类型 = 支付宝支付
    const PAY_TYPE_YUE                = 3;//支付类型 = 余额

    const REFUND_TYPE_YUANLU = 1;//退款方式:原路退回
    const REFUND_TYPE_XIANXIA = 2;//退款方式:线下退款

    /**
     * 押金下单
     * @param int $user_id 用户id
     * @param int $lease_order_id 订单id
    */
    public static function depositAdd($user_id,$lease_order_id = null){
        $amount = LeaseConfig::where(['id' => 1])->value('deposit');
        //添加订单
        $increase = [
            'user_id' => $user_id,
            'amount' => $amount,
            'status' => self::STATUS_WEIZHIFU,
            'deduction_fee' => 0,
            'refund_fee' => 0,
            'place_time' => time(),
            'createtime' => time(),
            'lease_order_id' => $lease_order_id,
        ];
        $deposit = self::create($increase);
        if (!$deposit){
            throw new Exception('押金记录生成失败');
            return false;
        }
        //添加定时任务
        $queue_default = config('queue.default');
        Queue::later(300, "addons\mycurrency\controller\job\Lease@depositPaymentVerification", ['deposit_id' => $deposit['id']], $queue_default);

        return $deposit;
    }


    /**
     * 押金支付成功后逻辑处理
     * @param int $deposit_id 押金支付记录id
     * @param int $pay_type 用户支付方式
     */
    public static function paymentSuccess($deposit_id,$pay_type){
        $deposit = self::where(['id' => $deposit_id,'deletetime' => null])->find();
        if(!$deposit){
            throw new Exception('记录不存在');
            return false;
        }
        if($deposit['status'] != self::STATUS_WEIZHIFU){
            throw new Exception('非待支付状态');
            return false;
        }

        //修改订单状态
        $deposit->pay_type = $pay_type;
        $deposit->status = self::STATUS_YIZHIFU;
        $deposit->payment_time = time();
        $deposit->save();

        //租赁订单处理
        trace(["20========================处理lease_order_id报错问题_paymentSuccess==============================" => $deposit],'error');
        if($deposit->lease_order_id != null){//押金支付成功，开始开锁
            //修改租赁订单状态

            LeaseOrder::where(['id' => $deposit->lease_order_id])->update([
                'use_status' => LeaseOrder::USE_STATUS_JINXINGZHONG,
            ]);
            //开始开锁
            trace(["========================处理lease_order_id报错问题_paymentSuccess 1==============================" => $deposit],'error');
            LeaseOrder::orderStartRenting($deposit->lease_order_id);
        }
    }

    /**
     * 申请退押金
     * @param int $deposit_id 押金记录id
    */
    public static function depositRefund($deposit_id){
        $deposit = self::where(['id' => $deposit_id,'deletetime' => null])->find();
        if(!$deposit){
            throw new Exception('充值记录不存在');
            return false;
        }
        if($deposit['status'] != self::STATUS_YIZHIFU){
            throw new Exception('非已支付状态');
            return false;
        }
        //修改充值记录状态
        $deposit->status = self::STATUS_TUIKUANGZHONG;
        $deposit->refund_time = time();
        $deposit->save();

        $refund_fee = $deposit->amount - $deposit->deduction_fee;//退款金额
        if($refund_fee <= 0){//没有需要退款的金额
            $deposit->status = self::STATUS_YIKOUKUAN;
            $deposit->save();
        }else{
            $deposit->refund_fee = $refund_fee;
            $deposit->save();

            //根据支付方式原路退回押金
            if($deposit->pay_type == self::PAY_TYPE_WECHAT || $deposit->pay_type == self::PAY_TYPE_ALIPAY){//押金支付方式 微信or支付宝 yss临时 未实现

            }elseif ($deposit->pay_type == self::PAY_TYPE_YUE){//余额支付
                //扣除用户余额
                UserMoneyLog::moneyChange($deposit['user_id'],$deposit->refund_fee,UserMoneyLog::TYPE_TUIHUIYAJIN,[
                    'memo' => '租赁陪护床押金退回',
                    'lease_deposit_id' => $deposit->id,
                ]);
                //处理押金退款成功后逻辑
                self::refundSuccess($deposit->id,self::REFUND_TYPE_YUANLU);
            }
        }



    }

    /**
     * 押金退款成功后逻辑处理
     * @param int $deposit_id 押金支付记录id
     * @param int $refund_type 退款方式:1=原路退回,2=线下退款【一些支付超过一年的有管理线下退款后更改状态】
     */
    public static function refundSuccess($deposit_id,$refund_type){
        $deposit = self::where(['id' => $deposit_id,'deletetime' => null])->find();
        if(!$deposit){
            throw new Exception('记录不存在');
            return false;
        }
        if($deposit['status'] != self::STATUS_TUIKUANGZHONG){
            throw new Exception('非退款中状态');
            return false;
        }

        //修改订单状态
        $deposit->refund_type = $refund_type;
        $deposit->status = self::STATUS_YITUIKUAN;
        $deposit->refund_complete_time = time();
        $deposit->save();

    }

    /**
     * 押金扣款
     * @param int $deposit_id 押金支付记录id
     * @param int $deduction_fee 扣款金额
    */
    public static function deduction($deposit_id,$deduction_fee){
        $deposit = self::where(['id' => $deposit_id,'deletetime' => null])->find();
        if(!$deposit){
            throw new Exception('押金记录不存在');
            return false;
        }
        if($deposit['status'] != self::STATUS_YIZHIFU){
            throw new Exception('押金非已支付状态');
            return false;
        }
        $deduction_fee = $deduction_fee <= $deposit->amount ? $deduction_fee : $deposit->amount;//处理扣款金额 如果扣款金额 大于押金支付金额 最多只能扣押金支付的最大金额

        //保存已扣款的金额
        $deposit->deduction_fee = $deduction_fee;
        $deposit->save();


        //调用退款接口
        self::depositRefund($deposit->id);

        return $deduction_fee;
    }

    //支付完成时间
    public function getPaymentTimeAttr($value){
        return $value != null ? date('Y-m-d H:i:s', $value) : '';
    }

    //退款完成时间
    public function getRefundCompleteTimeAttr($value){
        return $value != null ? date('Y-m-d H:i:s', $value) : '';
    }


    public function getStatusList()
    {
        return ['-1' => __('已取消'), '1' => __('未支付'), '2' => __('已支付'), '3' => __('已退款')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }



}
